package com.sinothk.fc.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.fc.browser.entity.BrowserEntity;
import com.sinothk.fc.browser.mapper.BrowserMapper;
import com.sinothk.fc.collect.entity.CollectEntity;
import com.sinothk.fc.collect.service.ICollectService;
import com.sinothk.fc.goods.entity.GoodsDTO;
import com.sinothk.fc.goods.entity.GoodsEntity;
import com.sinothk.fc.goods.entity.GoodsSearchReq;
import com.sinothk.fc.goods.entity.GoodsVO;
import com.sinothk.fc.goods.mapper.GoodsMapper;
import com.sinothk.fc.goods.service.IGoodsService;
import com.sinothk.fc.goodsLibrary.entity.GoodsLibraryEntity;
import com.sinothk.fc.goodsLibrary.service.IGoodsLibraryService;
import com.sinothk.fc.goodsStock.entity.GoodsStockClassifyVO;
import com.sinothk.fc.goodsStock.entity.GoodsStockEntity;
import com.sinothk.fc.goodsStock.service.IGoodsStockService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 产品信息
 * @Author: Liangyt
 * @Date: 2021-12-28
 * @Version: V1.0
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements IGoodsService {
    private final IGoodsLibraryService goodsLibraryService;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private IGoodsStockService goodsStockService;
    @Resource
    private BrowserMapper browserMapper;
    private final ICollectService collectService;

    @Autowired
    public GoodsServiceImpl(IGoodsLibraryService goodsLibraryService, ICollectService collectService) {
        this.goodsLibraryService = goodsLibraryService;
        this.collectService = collectService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GoodsEntity addOrEdit(GoodsEntity goodsEntity) throws Exception {
        if (StringUtils.isEmpty(goodsEntity.getGoodsNo())) throw new Exception("商品条形码不能为空");

        String goodsUrl = goodsEntity.getGoodsUrl();
        if (StringUtils.isNotBlank(goodsUrl) && StringUtils.isBlank(goodsEntity.getGoodsCover())) {
            // 封面获取
            String goodsCover = goodsUrl.split(",")[0];
            goodsEntity.setGoodsCover(goodsCover);
        }
        // 返回商品信息
        this.saveOrUpdate(goodsEntity);

        // 保存产品库 // 处理商品模板
        GoodsLibraryEntity goodsLibraryEntity = new GoodsLibraryEntity();
        BeanUtils.copyProperties(goodsEntity, goodsLibraryEntity);
        LambdaQueryWrapper<GoodsLibraryEntity> goodsLibraryWrapper = new LambdaQueryWrapper<>();
        goodsLibraryWrapper.eq(GoodsLibraryEntity::getGoodsNo, goodsEntity.getGoodsNo());

        GoodsLibraryEntity goodsLibraryEntityDB = goodsLibraryService.getOne(goodsLibraryWrapper);
        if (goodsLibraryEntityDB == null) {
            goodsLibraryService.save(goodsLibraryEntity);
        } else {
            goodsLibraryEntity.setId(goodsLibraryEntityDB.getId());
            goodsLibraryService.updateById(goodsLibraryEntity);
        }

        if (StringUtils.isNotBlank(goodsEntity.getGoodsName()) || StringUtils.isNotBlank(goodsEntity.getGoodsCover())) {
            // 更新库存名称
            LambdaUpdateWrapper<GoodsStockEntity> goodsStockUpdateWrapper = new LambdaUpdateWrapper<>();
            goodsStockUpdateWrapper.eq(GoodsStockEntity::getGoodsNo, goodsEntity.getGoodsNo());
            if (StringUtils.isNotBlank(goodsEntity.getGoodsName())) {
                goodsStockUpdateWrapper.set(GoodsStockEntity::getGoodsName, goodsEntity.getGoodsName());
            }
            if (StringUtils.isNotBlank(goodsEntity.getGoodsCover())) {
                String[] arr = goodsEntity.getGoodsCover().split(",");
                goodsStockUpdateWrapper.set(GoodsStockEntity::getGoodsCover, arr[0]);
            }
            goodsStockService.update(goodsStockUpdateWrapper);
        }

        return goodsEntity;
    }

    @Override
    public IPage<GoodsVO> getStoreAllGoodsByState(Page<GoodsEntity> page, GoodsSearchReq searchReq) throws Exception {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser == null) throw new Exception("当前用户信息有误");
        if (StringUtils.isBlank(loginUser.getStoreId())) throw new Exception("当前用户没有门店id");
        searchReq.setStoreId(loginUser.getStoreId());
        return goodsMapper.getStoreAllGoodsByState(page, searchReq);
    }

    @Override
    public IPage<GoodsEntity> supplierHomePage(Page<GoodsEntity> page, GoodsEntity goodsEntity) {
        LambdaQueryWrapper<GoodsEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsEntity::getState, GoodsEntity.STATE_ONLINE);
        queryWrapper.orderByDesc(GoodsEntity::getCreateTime);
        return this.page(page, queryWrapper);
    }

    @Override
    public IPage<GoodsEntity> supplierSearchHotPage(Page<GoodsEntity> page, GoodsEntity goodsEntity) {
        LambdaQueryWrapper<GoodsEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsEntity::getState, GoodsEntity.STATE_ONLINE);
        queryWrapper.orderByDesc(GoodsEntity::getCreateTime);
        return this.page(page, queryWrapper);
    }

    @Override
    public IPage<GoodsEntity> supplierSearchByKeywordsPage(Page<GoodsEntity> page, String keywords) {
        LambdaQueryWrapper<GoodsEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsEntity::getState, GoodsEntity.STATE_ONLINE);

        if (StringUtils.isNotBlank(keywords)) {
            queryWrapper.and(subWrapper -> {
                subWrapper.like(GoodsEntity::getGoodsName, keywords);
            });
        }

        queryWrapper.orderByDesc(GoodsEntity::getCreateTime);
        return this.page(page, queryWrapper);
    }

    @Override
    public GoodsDTO goodsShowDetail(String goodsId) throws Exception {
        GoodsDTO goodsVO = goodsMapper.goodsShowDetail(goodsId);

        // 查询收藏情况
        CollectEntity collect = collectService.getCurrCollectStateByGoodsId(goodsVO.getStoreId(), goodsId);
        goodsVO.setHasCollected(collect != null);

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser == null) throw new Exception("当前用户信息有误");

        // 新增商品浏览记录
        BrowserEntity goodsBrowser = new BrowserEntity();
        goodsBrowser.setStoreId(goodsVO.getStoreId());
        goodsBrowser.setGoodsId(goodsVO.getId());
        goodsBrowser.setCustomerId(loginUser.getId());
        browserMapper.insert(goodsBrowser);

        return goodsVO;
    }

    @Override
    public GoodsEntity goodsByBarCode(String barCode) throws Exception {
        LambdaQueryWrapper<GoodsEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsEntity::getGoodsNo, barCode);
        List<GoodsEntity> list = goodsMapper.selectList(queryWrapper);
        if (list == null || list.size() == 0) {
            throw new Exception("此商品没有录入到系统");
        } else if (list.size() == 1) {
            return list.get(0);
        } else {
            throw new Exception("错误！此条形码对应了多个商品");
        }
    }

    @Override
    public void updateGoodsNumToStockNumByBarcode(String barcode) throws Exception {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser == null) throw new Exception("当前用户信息有误");
        if (StringUtils.isBlank(loginUser.getStoreId())) throw new Exception("当前用户没有门店id");

        GoodsStockClassifyVO stockClassify = goodsStockService.getStockAllNumByBarcode(loginUser.getStoreId(), barcode);

        LambdaUpdateWrapper<GoodsEntity> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(GoodsEntity::getStoreId, loginUser.getStoreId());
        queryWrapper.eq(GoodsEntity::getGoodsNo, barcode);
        queryWrapper.set(GoodsEntity::getGoodsNum, (stockClassify == null || stockClassify.getGoodsAllNum() == null) ? 0 : stockClassify.getGoodsAllNum());
        this.update(queryWrapper);
    }

    @Override
    public IPage<GoodsVO> storeGoodsPageByStoreId(Page<GoodsEntity> page, String storeId) throws Exception {
        if (StringUtils.isBlank(storeId)) throw new Exception("当前用户没有门店id");
        return goodsMapper.storeGoodsPageByStoreId(page, storeId);
    }

    //    @Override
//    public GoodsStockEntity addOrEdit(GoodsStockEntity goodsStockEntity) {
//        String goodsUrl = goodsStockEntity.getGoodsUrl();
//        if (StringUtils.isNotBlank(goodsUrl)) {
//            // 封面获取
//            String goodsCover = goodsUrl.split(",")[0];
//            goodsStockEntity.setGoodsCover(goodsCover);
//        }
//        this.save(goodsStockEntity);
//
//        // 处理商品模板
//        GoodsLibraryEntity goodsLibraryEntity = new GoodsLibraryEntity();
//        BeanUtils.copyProperties(goodsStockEntity, goodsLibraryEntity);
//        goodsLibraryService.addOrEdit(goodsLibraryEntity);
//
//        return goodsStockEntity;
//    }
//
//    @Override
//    public IPage<GoodsStockEntity> storeGoodsStockPage(Page<GoodsStockEntity> page, GoodsStockEntity goodsReq) throws Exception {
//        if (StringUtils.isBlank(goodsReq.getStoreId())) throw new Exception("storeId必传");
//        LambdaQueryWrapper<GoodsStockEntity> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(GoodsStockEntity::getStoreId, goodsReq.getStoreId());
//        if (goodsReq.getState() != -1) {
//            queryWrapper.eq(GoodsStockEntity::getState, goodsReq.getState());
//        }
//        queryWrapper.orderByDesc(GoodsStockEntity::getCreateTime);
//        return this.page(page, queryWrapper);
//    }
}
